<?php
/**
 * 订单
 * User: Tsang
 * Date: 2017/10/30 15:50
 *
 */

namespace app\admin\controller;


use think\Db;

class Order extends Common
{

    /**
     * 订单列表
     */
    public function index(){
        $where = 'order_id > 0';
        $ordere_sn = input('sn/s');
        if(!empty($ordere_sn)){
            $where .= ' and order_sn = "'.$ordere_sn.'"';
        }
        $start_time = input('start/s');
        if(!empty($start_time)){
            $where .= ' and create_time > "'.$start_time.'"';
        }
        $end_time = input('end/s');
        if(!empty($end_time)){
            $where .= ' and create_time < "'.$end_time.'"';
        }
        $status = input('status/s');
        if($status != ''){
            if(!in_array($status,array(ORDER_STATUS_NOPAY,ORDER_STATUS_PAID,ORDER_STATUS_SENT,ORDER_STATUS_SUCCESS))) $this->error('非法操作');
            $where .= ' and order_state = "'.$status.'"';
        }

        $list = db('order')->where($where)->order('order_id desc')->paginate(20);
        $this->assign('list',$list);
        return $this->fetch();
    }


    /**
     * 订单详情
     */
    public function det(){
        $id = input('id/d');
        $data = db('order')->where(['order_id' => $id])->find();
        if(!$data) $this->error('找不到订单');
        $data['address'] = object_to_array(json_decode($data['address']));
        $data['remarks'] = htmlspecialchars_decode($data['remarks']);
        $data['goods'] = db('order_product')->where(['order_id' =>$data['order_id']])->select();
        $data['refund'] = array();
        if($data['refund_id'] > 0){
            $data['refund'] = db('refund')->where(['refund_id' => $data['refund_id'],'order_id' => $data['order_id']])->find();
            $data['refund']['images'] = json_decode($data['refund']['images']);
            foreach($data['refund']['images'] as &$fg){
                $fg = __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$fg);
            }
            if(!empty($data['refund']['reason'])){
                $data['refund']['reason'] = htmlspecialchars_decode($data['refund']['reason']);
            }

        }
        $data['goods'] = db('order_product')->where(['order_id' => $data['order_id']])->select();
        foreach($data['goods'] as &$og){
            if(!empty($og['product_img'])){
                $og['product_img'] = __ROOT__ . '/static/uploads'.str_replace('\\',"/",$og['product_img']);
            }
        }
        $this->assign('data',$data);
        return $this->fetch();
    }

    /**
     * 发货
     */
    public function sent(){
        $id = input('id/d');
        $m_order = db('order');
        $order = $m_order->where(['order_id' => $id])->find();
        if(!$order){
            echo json_encode(['msg' => '找不到订单','error' => -1]);
            exit;
        }
        if($order['order_state'] != ORDER_STATUS_PAID){
            echo json_encode(['msg' => '订单不是已付款状态','error' => -1]);
            exit;
        }
        if($order['refund_id'] > 0){
            echo json_encode(['msg' => '订单退款中','error' => -1]);
            exit;
        }
        $express_type = input('express_type/s');
        if(empty($express_type)){
            echo json_encode(['msg' => '快递方式不能为空','error' => -1]);
            exit;
        }
        $express_num = input('express_num/s');
        if(empty($express_num)) {
            echo json_encode(['msg' => '快递单号不能为空','error' => -1]);
            exit;
        }
        $data = array(
            'order_state' => ORDER_STATUS_SENT,
            'sent_time' => TIMESTAMP,
            'express_type' => htmlspecialchars($express_type),
            'express_num' => htmlspecialchars($express_num),
        );
        if($m_order->where(['order_id' => $id])->update($data) === false){
            echo json_encode(['msg' => '操作失败','error' => -1]);
        }else{
            echo json_encode(['error' => 0]);
        }
    }

    /**
     * 取消订单
     */
    public function cancel(){
        $id = input('id/d');
        $m_order = db('order');
        $order = $m_order->where(['order_id' => $id])->find();
        if(!$order) return array('message' => '找不到订单');
        if($order['order_state'] != ORDER_STATUS_NOPAY) return array('message' => '该订单不支持此操作');
        $order_goods = db('order_product')->where(['order_id' => $order['order_id']])->select();

        Db::startTrans();
        try{

            $m_order->where(['order_id' => $id])->update(['order_state' => ORDER_STATUS_CLOSE]);

            //加回库存
            $m_goods_option_value = db('goods_option_value');
            foreach($order_goods as $g){
                $m_goods_option_value->where(['goodsid' => $g['product_id'],'spec_name' => $g['spec']])->setInc('stock',$g['count']);
            }

            if($order['voucher_id'] > 0){
                $m_voucher = db('myvoucher');
                $voucher = $m_voucher->where(['id' => $order['voucher_id']])->find();
                if($voucher && $voucher['end_time'] > TIMESTAMP){
                    $m_voucher->where(['id' => $order['voucher_id']])->update(['status' => 0]);
                }
            }

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error('操作失败');
        }

        $this->redirect(url('order/index'));
    }


    /**
     * 退款列表
     */
    public function refund(){
        $where = array();
        $refund = db('refund')->alias('r')
            ->join('order o','o.order_id = r.order_id')
            ->where($where)
            ->order('r.refund_id desc')
            ->paginate(20);
        $this->assign('list',$refund);
        return $this->fetch();
    }

    /**
     * 退款详情
     */
    public function refund_det(){
        $id = input('id/d');
        $m_refund = db('refund');
        $data = $m_refund->alias('r')
            ->join('order o','o.order_id = r.order_id')
            ->where(['r.refund_id' => $id])
            ->order('r.refund_id desc')
            ->find();
        if ($this->request->isPost()) {
            if (intval($data['status']) != 0) $this->error('该订单已审核过');
            $status = input('status/d');
            if (!in_array($status, array(-1, 1))) $this->error('操作状态失败');
            Db::startTrans();
            try {
                $m_refund->where(['refund_id' => $id])->update(['status' => $status,'audit_time'  => TIMESTAMP]);

                /*if ($status == 1) {
                    $result = (new Pay($this->request))->wechat_refund($data['order_id'],$data['refund_sn']);
                    if(!$result) throw new \Exception('退款失败');
                }*/

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->redirect(url('order/refund'));
        }
        $this->assign('data',$data);
        return $this->fetch();
    }



}